import json
from functools import wraps
from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import HttpResponseRedirect, JsonResponse
from common.RedisHandler import RedisHandler
from user.models import User, UserDoLog

# 用户登录视图
# Create your views here.


def check_login(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        if request.session.get("user_id"):
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(reverse("user:login"))
    return inner


def login(request):
    if request.method == "POST":
        result = {"status": 0, "msg": "登录失败！"}
        try:
            data = json.loads(request.body)
            # print(data)
            phone = data.get("phone")
            password = data.get("password")
            # ver_code = data.get("ver_code")
            # conn = RedisHandler().conn
            # if not conn.exists(ver_code.upper()):
            #     result["msg"] = "验证码无效！"
            #     return JsonResponse(result)
            user = User.objects.filter(phone=phone, password=password, is_delete=0, status=1).first()
            if user:
                request.session["user_id"] = user.id
                user_do = UserDoLog.objects.create(what="用户登录", who=user.name)
                user_do.save()
                result["status"] = 1
                result["msg"] = "登录成功！"
            else:
                result["msg"] = "用户名或密码错误！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
        # return HttpResponseRedirect(reverse("home:index"))
    else:
        return render(request, "user/login.html")


def logout(request):
    request.session.flush()
    return HttpResponseRedirect(reverse("user:login"))

